package com.xml.util;

import gridreport.BinaryObject;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.net.URLEncoder;

/**
 * GridReport工具类
 * @author 夏明龙 E-Mail:kaioct@qq.com
 * @date 2021/3/6
 * @desc gridReportServerJava
 * @created 2021-03-06 18:15
 **/
public class ServerUtility {
    // 将报表生成的二进制数据响应给 HTPP 请求客户端
    // <param name="context"> HTPP 请求对象</param>
    // <param name="ExportResult">报表生成的二进制数据</param>
    // <param name="FileName">指定下载(或保存)文件时的默认文件名称</param>
    // <param name="contentType">响应的ContentType</param>
    // <param name="OpenMode">指定生成的数据打开模式，可选[inline|attachment]，"inline"表示在网页中内联显示，"attachment"表示以附件文件形式下载。如果不指定，由浏览器自动确定打开方式。</param>
    static public void ResponseBinary(HttpServletRequest request, HttpServletResponse response,
                                      BinaryObject bo, String FileName, String contentType, String OpenMode) throws Exception {
        if (bo.getDataSize() > 0) {
            String Disposition = "";

            if (OpenMode != null && OpenMode.length() > 0)
                Disposition = OpenMode + "; ";

            String UserAgent = request.getHeader("User-Agent"); //?这样是否可行 context.Request.UserAgent
            Disposition += EncodeAttachmentFileName(UserAgent, FileName);

            response.setContentType(contentType);
            response.addHeader("Content-Length", new Integer(bo.getDataSize()).toString());
            response.addHeader("Content-Disposition", Disposition);

            response.resetBuffer();

            ServletOutputStream os = response.getOutputStream();
            os.write(bo.getDataBuf());
            os.flush();
        } else {
            ResponseException(response, "Failed to generate report.");
        }
    }

    // 将异常信息文字响应给请求的客户端
    // <param name="context"></param>
    // <param name="MessageText"></param>
    public static void ResponseException(HttpServletResponse response, String MessageText) throws Exception {
        //try {
        //response.setContentType("text/plain");
        PrintWriter pw = response.getWriter();
        pw.print(MessageText);
        pw.close();  //终止后续不必要内容输出
        //}
        //catch(Exception e) {
        //out.println(e.toString());
        //}
    }

    // 为了文件名中的汉字与特殊字符能正确，必须进行分浏览器处理
    // <param name="browserAgent"></param>
    // <param name="RawFileName"></param>
    // <returns></returns>
    public static String EncodeAttachmentFileName(String browserAgent, String RawFileName) throws Exception {
        String EncodedFileName = URLEncoder.encode(RawFileName, "utf-8");

        // 如果没有browserAgent，则默认使用IE的方式进行编码，因为毕竟IE还是占多数的
        String ret = "filename=\"" + EncodedFileName + "\"";
        if (browserAgent != null && browserAgent.length() > 0) {
            browserAgent = browserAgent.toLowerCase();
            // msie 与 edge 采用默认的方式
            if (!browserAgent.contains("msie") && !browserAgent.contains("edge")) {
                // Chrome浏览器，只能采用MimeUtility编码或ISO编码的中文输出
                if (browserAgent.contains("applewebkit")) {
                    //TODO...EncodedFileName = MimeUtility.encodeText(RawFileName, "UTF8", "B"); //？javax.mail.internet.MimeUtility这个不能用，造成chrome下载不成功
                    //ret = "filename*=UTF-8''" + EncodedFileName.replaceAll("\\+", "%20");
                    //ret = "filename=" + EncodedFileName.replaceAll("\\+", "%20");
                    //ret = "filename=\"" + RawFileName + "\"";
                }
                // Safari浏览器，只能采用ISO编码的中文输出
                else if (browserAgent.contains("safari")) {
                    //28591  iso-8859-1                1252   *
                    ret = "filename=\"" + new String(EncodedFileName.getBytes("UTF-8"), "ISO8859-1") + "\"";
                    //byte[] UTF8Bytes = UTF8Encoding.GetBytes(RawFileName);
                    //String ISO8859Text = System.Text.Encoding.GetEncoding(28591).GetString(UTF8Bytes);
                    //ret = "filename=\"" + ISO8859Text + "\"";
                }
                // Opera浏览器只能采用filename*
                // FireFox浏览器，可以使用MimeUtility或filename*或ISO编码的中文输出
                else if (browserAgent.contains("opera") || browserAgent.contains("mozilla")) {
                    ret = "filename*=UTF-8''" + EncodedFileName;
                }
            }
        }

        return ret;
    }
}
